package com.boliq.lol.adapter;

import android.util.SparseArray;
import android.view.MenuItem;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;

import com.boliq.lol.ui.news.NewsMainFragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import java.lang.ref.WeakReference;
public class MainVpAdapter extends FragmentPagerAdapter {
    private final SparseArray<Fragment> mFragmentCache;
    private WeakReference<BottomNavigationView> mWeakReference;

    public MainVpAdapter(@NonNull FragmentManager fm) {
        super(fm, FragmentPagerAdapter.BEHAVIOR_SET_USER_VISIBLE_HINT);
        mFragmentCache = new SparseArray<>();
    }

    @NonNull
    @Override
    public Fragment getItem(int position) {
        Fragment fragment = null;
        if(isWeakOn()){
            MenuItem menuBean = mWeakReference.get().getMenu().getItem(position);
            int id = menuBean.getItemId();
            fragment = mFragmentCache.get(id);
            if (fragment == null) {
                fragment = createFragment(id);
                mFragmentCache.put(id, fragment);
            }

        }

        return fragment;
    }

    private Fragment createFragment(int id) {
        Fragment fragment = new NewsMainFragment();
        return fragment;
    }

    @Override
    public int getCount() {
        if(isWeakOn()){
            return mWeakReference.get().getMenu().size();
        }
        return 0;
    }

    private boolean isWeakOn() {
        return mWeakReference != null && mWeakReference.get() != null;
    }

    public void attachNav(BottomNavigationView navigationView) {
        if (mWeakReference != null) {
            if (mWeakReference.get() == navigationView) {
                return;
            }
            mWeakReference.clear();
        }
        mWeakReference = new WeakReference<>(navigationView);
        notifyDataSetChanged();
    }
}